import vtk
from pyNastran.bdf.bdf import BDF


def bdf_to_vtk(bdf_file_path):
    # 读取 BDF 文件
    bdf = BDF()
    bdf.read_bdf(bdf_file_path)

    # 创建 VTK 的点数据
    points = vtk.vtkPoints()
    # 创建 VTK 的单元数据
    cells = vtk.vtkCellArray()

    # 添加节点信息到 VTK 点数据
    for node_id, node in bdf.nodes.items():
        x, y, z = node.get_position()
        points.InsertNextPoint(x, y, z)

    # 添加单元信息到 VTK 单元数据
    for element_id, element in bdf.elements.items():
        if element.type in ['CQUAD4', 'CTRIA3']:  # 仅处理四边形和三角形单元
            connectivity = element.node_ids
            if element.type == 'CQUAD4':
                cell = vtk.vtkQuad()
            elif element.type == 'CTRIA3':
                cell = vtk.vtkTriangle()
            for i, node_id in enumerate(connectivity):
                cell.GetPointIds().SetId(i, bdf.nodes[node_id].id - 1)
            cells.InsertNextCell(cell)

    # 创建 VTK 的多边形数据
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetPolys(cells)

    return polydata


# 使用示例
bdf_file_path = 'your_file.bdf'
polydata = bdf_to_vtk(bdf_file_path)

# 创建映射器和演员
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(polydata)

actor = vtk.vtkActor()
actor.SetMapper(mapper)

# 创建渲染器和渲染窗口
renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)

# 创建交互器
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)

# 将演员添加到渲染器
renderer.AddActor(actor)
renderer.SetBackground(0.1, 0.2, 0.3)

# 开始交互
renderWindow.Render()
renderWindowInteractor.Start()